package cn.genmer.test.security.controller;

import cn.genmer.test.security.model.excel.Dept;
import com.alibaba.excel.EasyExcel;
import com.google.common.collect.Lists;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

@RestController
public class ExcelWriteController {

    /**
     * 下载excel文件
     */
    @GetMapping("/excel")
    public void doDownLoad(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("部门信息文件", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //以下三条语句可以转化为一条语句
        //ExcelWriterBuilder write = EasyExcel.write(response.getOutputStream(), Dept.class);
        //ExcelWriterSheetBuilder excelWriterSheetBuilder = write.sheet("部门信息");
        //excelWriterSheetBuilder.doWrite(getList());//参数为Dept的对象数组
        //可以转化为
        EasyExcel.write(response.getOutputStream(), Dept.class).sheet("部门信息").doWrite(getList());
    }

    /**
     * 构造假数据
     * @return List<UserEntity>
     */
    private List<Dept> getList() {
        List<Dept> depts = Lists.newArrayList();
        for (int i = 1;i <= 20; i++ ){
            if(i%2==0){
                Dept dept = new Dept().setLoc("微信公众号：搜索" + i + "次").setDname("程序员小哲").setBirthday(new Date()).setDeptno(i * 10).setMoney(8888 + i * 1000);
                depts.add(dept);
            }else {
                Dept dept = new Dept().setLoc("百度：搜索"+i+"次").setDname("程序员小哲").setBirthday(new Date()).setDeptno(i*10).setMoney(8888+i*1000);
                depts.add(dept);
            }
        }
        return depts;
    }

}
